package com.tc.gateway.tunnel;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class MultiInputStream extends InputStream{

	InetAddress group = null;
	MulticastSocket socket = null;
	PipedOutputStream out = new PipedOutputStream();
	PipedInputStream in = new PipedInputStream();
int port;
	public MultiInputStream(InetAddress g,	MulticastSocket s, int po)
	{
		this.group = g;
		this.socket = s;
		this.port = po;
		try {
			in.connect(out);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		new Thread(){

			@Override
			public void run() {


				while(true){
					byte[] buf = new byte[2048];
					DatagramPacket dgram = new DatagramPacket(buf, buf.length);
				try {
					socket.receive(dgram);
					String s = new String(buf, 0, dgram.getLength());
//					if(s.length() <= 10){
//						System.err.println(s);
//						continue;
//					}
					out.write(dgram.getData(), dgram.getOffset(), dgram.getLength());
					out.flush();
					System.err.println("Received " + dgram.getLength() +
						    " bytes from " + dgram.getAddress());

					this.sleep(1000);
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				}
				
			}
			
		}.start();
		
		
	}
	@Override
	public int read() throws IOException {
		

		return in.read();

	}

	
	@Override
	public int read(byte[] bytes, int offset, int count) throws IOException {
		return in.read(bytes, offset, count);
		
	}
	@Override
	public int read(byte[] b) throws IOException {
		return in.read(b);
	}
	
}
